<style lang="stylus" scoped>
@import '../../styl/var.styl'

li
  margin-bottom 7px

  &>label
    background url('!/svg/record/video.svg') 50% 44% / 40px no-repeat bg
    position relative
    border-radius 8px
    border 1px solid #F3F5F7
    width 54px
    margin-right 12px
    overflow hidden
    cursor pointer
    display flex

    &.x:before,&>a.x
      height 100%
      width 100%
      content ''
      position absolute
      background url('!/svg/x.svg') 50% 10px / 25px no-repeat

    &.e:after
      background none

  &.audio
    &>label
      background-image url('!/svg/record/audio.svg')
      display flex
      &>a
        flex 1
</style>

<template lang="pug">
.bk
  h2 设备设置
  li.video
    label(:class="{ x: !config.video }" @click="x('video')" for="driveVideo")
    .select
      select#driveVideo(@focus="refresh" v-model="config.video")
        optgroup(label="输入源")
          option(:value="id" v-for="[id, label] in video") {{ label }}
        optgroup(label="───")
          option(value) 禁用
  li.audio
    label(
      @click="x('audio')"
      for="driveAudio"
    )
      z-audio
    .select
      select#driveAudio(@focus="refresh" v-model="config.audio")
        optgroup(label="输入源")
          option(:value="id" v-for="[id, label] in audio") {{ label }}
        optgroup(label="───")
          option(value) 禁用
</template>

<script lang="coffee">

import zAudio from '~/vue/audio.vue'
import config from '~/store/record.coffee'
import ipc from '~/lib/ipc.coffee'
import media_by_id from '~/lib/media_by_id.coffee'

export default {
components:{zAudio}
setup:=>

  select = {
    audio : shallowRef []
    video : shallowRef []
  }

  {mediaDevices} = navigator

  refresh = =>
    li = {}
    for {kind,label,deviceId} from await mediaDevices.enumerateDevices()
      if deviceId == 'default'
        label = label.replace('Default - ','默认 ')
      if kind.endsWith('input')
        kind = kind[..-6]
        (li[kind] = li[kind] or []).push [deviceId,label]

    for k of select
      select[k].value = li[k] or []

    for k of select
      {value} = select[k]
      if value.length
        v = config[k]
        if v
          for [i] from value
            if v == i
              return
        if v!=''
          v = value[0][0]
      else
        v = 0
      config[k] = v

    return


  watchEffect =>
    for i from ['audio','video']
      v = config[i]
      if v
        localStorage[i] = v
    return


  do =>
    await refresh()
    return

  {
    refresh
    config
    x:(kind)=>
      v = config[kind]
      if v
        v = ''
      else
        v = localStorage[kind] or ''
      config[kind] = v
      return
    ...select
  }
}
</script>
